//
//  LMStationViewController.m
//  EPA
//
//  Created by lanou3g on 16/4/21.
//  Copyright © 2016年 liman. All rights reserved.
//

#import "LMStationViewController.h"
#import "LMRadioCell.h"
#import "LMStationListModel.h"
#import "LMNetWorkRequestManager.h"
#import "LMCycleView.h"
#import "LMRadioController.h"
#import "LORefresh.h"

@interface LMStationViewController ()<UICollectionViewDataSource,UICollectionViewDelegate>
@property (nonatomic, strong)UICollectionView *collectionView;

@property (nonatomic, strong) NSMutableArray *stationArray;

@property (nonatomic, strong)LMCycleView  *cycleView;

@property (nonatomic, strong) NSString *start;
@end

@implementation LMStationViewController

static NSString * const reuseIdentifier = @"Cell";
- (void)viewDidLoad {
    [super viewDidLoad];
    self.stationArray = [NSMutableArray new];
    [self loadDataFormServer];
    [self setupCollectionLayout];
    
    [self loadMore];
}
- (void)setupCollectionLayout{
    UICollectionViewFlowLayout *flowLayout = [UICollectionViewFlowLayout new];
    flowLayout.minimumInteritemSpacing = 1;
    flowLayout.minimumLineSpacing = 1;
    flowLayout.sectionInset = UIEdgeInsetsMake(1, 1, 1, 1);
    flowLayout.itemSize = CGSizeMake(self.view.frame.size.width * 0.33, self.view.frame.size.height * 0.33);
    //    设置Header的高度
    flowLayout.headerReferenceSize = CGSizeMake(self.view.frame.size.width, 200);
    
    self.collectionView  = [[UICollectionView alloc]initWithFrame:self.view.bounds collectionViewLayout:flowLayout];
    
    self.collectionView .delegate = self;
    self.collectionView .dataSource = self;
    UIImage *image = [UIImage imageNamed:@"IMG_0091.JPG"];
    self.collectionView .backgroundColor = [UIColor colorWithPatternImage:[image applyDarkEffect]];
    //    注册cell
    [self.collectionView  registerNib:[UINib nibWithNibName:@"LMRadioCell" bundle:nil] forCellWithReuseIdentifier:reuseIdentifier];
    //    注册头
    [self.collectionView  registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"header"];
    
    [self.view addSubview:self.collectionView ];
}



#pragma  mark - 解析shuju
//第一次显示数据的解析
- (void)loadDataFormServer{
    [LMNetWorkRequestManager requestURL:[NSURL URLWithString:RADIOLIST_URL] Method:LM_POST Params:@{@"client":@"1",@"deviceid":@"63A94D37-33F9-40FF-9EBB-481182338873",@"auth":@"",@"version":@"3.0.2"}
                                 Result:^(NSData *data, NSURLResponse *response, NSError *error) {
                                     NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
                                     NSDictionary *dataDict = jsonDict[@"data"];
                                     for (NSDictionary *item in dataDict[@"alllist"]) {
                                         LMStationListModel *model = [[LMStationListModel alloc]init];
                                         [model setValuesForKeysWithDictionary:item];
                                         [self.stationArray addObject:model];
                                     }
                                     dispatch_async(dispatch_get_main_queue(), ^{
                                         [self.collectionView reloadData];
                                     });
                                     
                                 }];
}
//加载数据时的解析
- (void)loadDataFormServerStart :(NSString *)start{
    NSDictionary *params = [NSDictionary dictionary];
    if ([UserInfoManager shareManager].auth) {
        params =@{@"auth":[UserInfoManager shareManager].auth ,@"client":@"1",@"deviceid":@"6D4DD967-5EB2-40E2-A202-37E64F3BEA31",@"limit":@"9",@"start":start,@"version":@"3.0.6"} ;
    }else{
        params = @{@"auth":@"",@"client":@"1",@"deviceid":@"6D4DD967-5EB2-40E2-A202-37E64F3BEA31",@"limit":@"9",@"start":start,@"version":@"3.0.6"} ;
    }
    [LMNetWorkRequestManager requestURL:[NSURL URLWithString:RADIOMLISTORE_URL] Method:LM_POST Params:params Result:^(NSData *data, NSURLResponse *response, NSError *error) {
        NSLog(@"%@",data);
  
        NSMutableDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        NSLog(@"%@",jsonDict);
        NSDictionary *dataDict = jsonDict[@"data"];
        for (NSDictionary *item in dataDict[@"list"]) {
            LMStationListModel *model = [[LMStationListModel alloc]init];
            [model setValuesForKeysWithDictionary:item];
            NSLog(@"%@",model.title);
            [self.stationArray addObject:model];
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.collectionView reloadData];
            [[self.collectionView defaultFooter] endRefreshing];
        });

    }];
    
}

#pragma  mark - 加载
-(void)loadMore{
    __weak typeof(self) weakSelf =self;
    [self.collectionView addRefreshWithRefreshViewType:LORefreshViewTypeFooterDefault refreshingBlock:^{
        NSInteger count = weakSelf.stationArray.count;
        weakSelf.start = [NSString stringWithFormat:@"%ld",count];
        [weakSelf loadDataFormServerStart:weakSelf.start];
    }];
}
//释放
- (void)dealloc{
    [self.collectionView removeObserver:[self.collectionView defaultFooter] forKeyPath:@"contentOffset"];
    [self.collectionView removeObserver:[self.collectionView defaultFooter] forKeyPath:@"contentSize"];

}


#pragma  mark - 代理
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 1;
}


- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.stationArray.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    LMRadioCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:reuseIdentifier forIndexPath:indexPath];
    
    cell.model = self.stationArray[indexPath.row];
    
    return cell;
}
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath{
    if ([kind isEqualToString:UICollectionElementKindSectionHeader]) {
        //创建头部轮播图
        self.cycleView = [[LMCycleView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 200) interVal:3];
        self.cycleView.imgNameArray = [@[@"1.jpg",@"2.jpg",@"3.jpg",@"4.jpg",@"5.jpg",@"6.jpg"] mutableCopy];
        UICollectionReusableView *header = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"header" forIndexPath:indexPath];
        [header addSubview:self.cycleView];
        return header;
    
    }
    return nil;
}

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    LMRadioController *radioVC = [[LMRadioController alloc]init];
    LMStationListModel *model = self.stationArray[indexPath.row];
    radioVC.radioId = model.radioid;
    [self.navigationController pushViewController:radioVC animated:YES];
}


@end
